package com.agileai.portal.controller.auth;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.BooleanUtils;

import com.agileai.common.AppConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.controller.core.TreeAndContentManageListHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.filter.UserCacheManager;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.ListUtil;

public class SecurityGroupListHandler
        extends TreeAndContentManageListHandler {
    public SecurityGroupListHandler() {
        super();
        this.serviceId = buildServiceId(SecurityGroupManage.class);
        this.rootColumnId = "00000000-0000-0000-00000000000000000";
        this.defaultTabId = SecurityGroupManage.BASE_TAB_ID;
        this.columnIdField = "GRP_ID";
        this.columnNameField = "GRP_NAME";
        this.columnParentIdField = "GRP_PID";
        this.columnSortField = "GRP_SORT";
    }

    protected void processPageAttributes(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("SecurityUser".equals(tabId)) {
            initMappingItem("USER_SEX",
                            FormSelectFactory.create("USER_SEX").getContent());
            initMappingItem("USER_STATE",
                            FormSelectFactory.create("SYS_VALID_TYPE")
                                             .getContent());
        }

        setAttribute("GRP_STATE",
                     FormSelectFactory.create("SYS_VALID_TYPE")
                                      .addSelectedValue(getOperaAttributeValue("GRP_STATE",
                                                                               "1")));
    }

    protected void initParameters(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("SecurityUser".equals(tabId)) {
            initParamItem(param, "columnId", "");
            initParamItem(param, "userCode", "");
            initParamItem(param, "userName", "");
        }
    }

    protected TreeBuilder provideTreeBuilder(DataParam param) {
        SecurityGroupManage service = this.getService();
        List<DataRow> menuRecords = service.findTreeRecords(new DataParam());
        TreeBuilder treeBuilder = new TreeBuilder(menuRecords,
                                                  this.columnIdField,
                                                  this.columnNameField,
                                                  this.columnParentIdField);

        return treeBuilder;
    }

    
	public ViewRenderer doDeleteAction(DataParam param){
		DataRow record = getService().getContentRecord("SecurityUser",param);
		String userCode = record.getString("USER_CODE");
		UserCacheManager.getOnly().removeUser(userCode);
		
		AppConfig appConfig = (AppConfig)this.lookupService("appConfig");
		String enableUserInfoSync = appConfig.getConfig("UnifiedUserIntegrateConfig", "EnableUserInfoSync");
		if (enableUserInfoSync != null){
			if (BooleanUtils.toBoolean(enableUserInfoSync)){
				try {
		    		UserSync userSync = UserSyncHelper.getUserSyncService();
		    		String tokenId = UserSyncHelper.genTokenId("removeUser");
		    		userSync.removeUser(tokenId, userCode);
				} catch (Exception e) {
					log.error(e.getLocalizedMessage(), e);
				}
			}
		}
		return super.doDeleteAction(param);
	}    
	
	public ViewRenderer doMoveContentAction(DataParam param){
		UserCacheManager.getOnly().truncateUsers();
		return super.doMoveContentAction(param);
	}
	
	public ViewRenderer doCopyContentAction(DataParam param){
		UserCacheManager.getOnly().truncateUsers();
		return super.doCopyContentAction(param);
	}
	
	public ViewRenderer doRemoveContentAction(DataParam param){
		UserCacheManager.getOnly().truncateUsers();
		return super.doRemoveContentAction(param);
	}
	
	public ViewRenderer doDeleteTreeNodeAction(DataParam param){
		String rspText = SUCCESS;
		String columnId = param.get("columnId");
		TreeAndContentManage service = this.getService();
		List<DataRow> childRecords =  service.queryChildTreeRecords(columnId);
		if (!ListUtil.isNullOrEmpty(childRecords)){
			rspText = "hasChild";
			return new AjaxRenderer(rspText);
		}
		List<String> tabList = this.getTabList();
		for (int i=0;i < tabList.size();i++){
			String tabId = tabList.get(i);
			if (TreeAndContentManage.BASE_TAB_ID.equals(tabId))continue;
			List<DataRow> records = service.findContentRecords(null,tabId, new DataParam("columnId",columnId));
			if (!ListUtil.isNullOrEmpty(records)){
				rspText = "hasContent";
				return new AjaxRenderer(rspText);
			}			
		}
		service.deleteTreeRecord(columnId);
		UserCacheManager.getOnly().truncateUsers();
		return new AjaxRenderer(rspText);
	}
	
	public ViewRenderer doMoveTreeAction(DataParam param){
		String rspText = SUCCESS;
		String columnId = param.get("columnId");
		String targetParentId = param.get("targetParentId");
		TreeAndContentManage service = this.getService();
		int newMaxSortId = service.retrieveNewMaxSort(targetParentId);
		DataParam queryParam = new DataParam(columnIdField,columnId);
		DataRow row = service.queryTreeRecord(queryParam);
		row.put(this.columnSortField,newMaxSortId);
		row.put(this.columnParentIdField,targetParentId);
		service.updateTreeRecord(row.toDataParam(true));
		UserCacheManager.getOnly().truncateUsers();
		return new AjaxRenderer(rspText);
	}	
	
    protected List<String> getTabList() {
        List<String> result = new ArrayList<String>();
        result.add(SecurityGroupManage.BASE_TAB_ID);
        result.add("SecurityUser");

        return result;
    }

    protected SecurityGroupManage getService() {
        return (SecurityGroupManage) this.lookupService(this.getServiceId());
    }
}
